package com.js.rtu.fragment.second;

import android.os.Bundle;
import android.widget.EditText;

import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.util.BleUtils;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 23_20终端出厂编号
 * 18 位
 */
public class Cmd_23_20Fragment extends BaseFragment {


    @BindView(R.id.edt_input)
    EditText edtInput;


    public static Cmd_23_20Fragment newInstance() {
        Cmd_23_20Fragment fragment = new Cmd_23_20Fragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_second_cmd_23_20;
    }

    @Override
    protected void initView() {

    }


    private void set() {
        String data = edtInput.getText().toString();
        if (data.length() != 18) {
            toastShow("请填写18位");
            return;
        }
        long interval = Long.parseLong(data);
        data = String.format(Locale.CHINA, "%018d", interval);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.length(); i++) {
            stringBuilder.append(BleUtils.strToASCII(data.substring(i, i + 1)))
                    .append(" ");
        }

        String msg = CmdConfig.CMD_23_20 + " " + stringBuilder.toString().substring(0, stringBuilder.length() - 1);
        sendData(msg);

    }

    private void sendData(String data) {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_23, data);
        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                dismissLoadingDialog();
                String[] data = msg.split(" ");
                if (data.length < 18) {
                    toastShow(msg);
                    return;
                }
                if (data[12].equals(CmdConfig.CMD_23)
                        && data[13].equals(CmdConfig.CMD_23_20)) {
                    if (data[14].equals(CmdConfig.SUCCECC)) {
                        toastShow("设置成功");
                    } else {
                        toastShow("设置失败");
                    }

                }
            }

            @Override
            public void onFail(String err) {
                toastShow(err);
                dismissLoadingDialog();
            }
        });
    }


    @OnClick(R.id.btn_set)
    public void onViewClicked() {
        set();
    }


}
